package com.swind.fast.modules.app.railway.project.listener;

import com.swind.fast.common.util.oConvertUtils;

import com.swind.fast.modules.app.railway.project.component.RailwayComponent;
import com.swind.fast.modules.app.railway.project.constant.ProjectStatusEnum;
import com.swind.fast.modules.app.railway.project.vo.RailwayProjectStatusVo;
import com.swind.fast.modules.app.railway.project.event.ProjectStatusEvent;
import com.swind.fast.modules.app.railway.project.entity.RailwayProject;
import com.swind.fast.modules.app.railway.project.entity.RailwayProjectOperationLog;

import com.swind.fast.modules.app.railway.project.service.IRailwayProjectService;
import com.swind.fast.modules.app.railway.project.service.IRailwayProjectOperationLogService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Async;
import org.springframework.context.event.EventListener;

import org.springframework.context.ApplicationEvent;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ProjectListener {

    @Autowired
    private RailwayComponent railwayComponent;

    @Autowired
    private IRailwayProjectService railwayProjectService;

    @Autowired
    private IRailwayProjectOperationLogService railwayProjectOperationLogService;

    @Async
    @EventListener
    public void projectStatusListener(ProjectStatusEvent event) {
        log.info("projectStatusListener");

        RailwayProjectStatusVo projectStatus = (RailwayProjectStatusVo) event.getSource();
        String projectId = projectStatus.getProjectId();
        ProjectStatusEnum status = projectStatus.getProjectStatusEnum();

        RailwayProject project = railwayProjectService.getById(projectId);
        Integer fstatus = project.getStatus();
        Integer pstatus = status.getValue();
        log.info("project: {}, status: {}", project, pstatus);

        // UpdateWrapper<RailwayProject> itemWrapper = new UpdateWrapper<RailwayProject>().set("status", pstatus).eq("id", id);
        // railwayProjectService.update(itemWrapper);

        project.setStatus(pstatus);
        railwayProjectService.updateById(project);

        String memo = projectStatus.getMemo();
        String createBy = projectStatus.getCreateBy();
        RailwayProjectOperationLog operationLog = new RailwayProjectOperationLog(projectId, fstatus, pstatus, memo, createBy);
        railwayProjectOperationLogService.save(operationLog);

        // log.info("username: {}", railwayComponent.getUserRealname());
    }

}
